﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MesProjectWinform.Public.Common;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;
using System.Net.Http;
using System.IO;

namespace MesProjectWinform.BasicData.基础实现.kehu
{
    public partial class kehu : DevExpress.XtraEditors.XtraForm
    {
        // 分页参数
        private int pageIndex = 1;     // 当前页码
        private int pageSize = 5;      // 每页数量
        private int totalCount = 0;    // 总记录数
        private int totalPages = 0;    // 总页数
        private Label lblPageInfo;     // 页码信息标签
        private TextBox txtPageSize;   // 页容量输入框
        private Button btnChangePageSize; // 修改页容量按钮

        public kehu()
        {
            InitializeComponent();
            InitializePageControls();
            this.Load += Kehu_Load;
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitializePageControls()
        {
            // 布局参数
            int buttonWidth = 80;
            int buttonHeight = 30;
            int buttonSpacing = 20;
            int yPosition = 28;
            
            // 添加首页按钮
            Button btnFirst = new Button();
            btnFirst.Size = new Size(buttonWidth, buttonHeight);
            btnFirst.Location = new Point(30, yPosition);
            btnFirst.Text = "首页";
            btnFirst.Click += BtnFirst_Click;
            panelControl3.Controls.Add(btnFirst);
            
            // 上一页按钮
            button3.Text = "上一页";
            button3.Size = new Size(buttonWidth, buttonHeight);
            button3.Location = new Point(btnFirst.Right + buttonSpacing, yPosition);
            
            // 创建页码信息标签（放在中间）
            lblPageInfo = new Label();
            lblPageInfo.AutoSize = true;
            int centerX = panelControl3.Width / 2 - 150; // 大致居中
            lblPageInfo.Location = new Point(centerX, yPosition + 5);
            lblPageInfo.Font = new Font(lblPageInfo.Font.FontFamily, 10);
            lblPageInfo.Text = "总记录数: 0   总页数: 0   当前页: 1";
            panelControl3.Controls.Add(lblPageInfo);
            
            // 下一页按钮
            button4.Text = "下一页";
            button4.Size = new Size(buttonWidth, buttonHeight);
            button4.Location = new Point(centerX + 300, yPosition);
            
            // 添加尾页按钮
            Button btnLast = new Button();
            btnLast.Size = new Size(buttonWidth, buttonHeight);
            btnLast.Location = new Point(button4.Right + buttonSpacing, yPosition);
            btnLast.Text = "尾页";
            btnLast.Click += BtnLast_Click;
            panelControl3.Controls.Add(btnLast);
            
            // 创建页容量输入框标签（放在下一页按钮后面）
            Label lblPageSize = new Label();
            lblPageSize.AutoSize = true;
            lblPageSize.Location = new Point(btnLast.Right + buttonSpacing * 2, yPosition + 5);
            lblPageSize.Font = new Font(lblPageSize.Font.FontFamily, 10);
            lblPageSize.Text = "每页显示:";
            panelControl3.Controls.Add(lblPageSize);
            
            // 创建页容量输入框
            txtPageSize = new TextBox();
            txtPageSize.Location = new Point(lblPageSize.Right + 5, yPosition + 3);
            txtPageSize.Size = new Size(50, 25);
            txtPageSize.Text = pageSize.ToString();
            panelControl3.Controls.Add(txtPageSize);
            
            // 创建修改页容量按钮
            btnChangePageSize = new Button();
            btnChangePageSize.Location = new Point(txtPageSize.Right + 10, yPosition);
            btnChangePageSize.Size = new Size(100, buttonHeight);
            btnChangePageSize.Text = "修改页容量";
            btnChangePageSize.Click += BtnChangePageSize_Click;
            panelControl3.Controls.Add(btnChangePageSize);
        }

        private void Kehu_Load(object sender, EventArgs e)
        {
            // 窗口加载时获取数据
            LoadData();
            
            // 窗体加载完成后，重新布局控件以确保位置正确
            this.Shown += (s, args) => {
                // 重新布局，以确保中间的标签位置正确
                if (lblPageInfo != null)
                {
                    int centerX = panelControl3.Width / 2 - lblPageInfo.Width / 2;
                    lblPageInfo.Location = new Point(centerX, lblPageInfo.Location.Y);
                }
            };
        }
        
        /// <summary>
        /// 修改页容量按钮点击事件
        /// </summary>
        private void BtnChangePageSize_Click(object sender, EventArgs e)
        {
            if (int.TryParse(txtPageSize.Text, out int newSize) && newSize > 0)
            {
                pageSize = newSize;
                pageIndex = 1; // 重置为第一页
                LoadData();
            }
            else
            {
                MessageBox.Show("请输入有效的页容量数值！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        
        /// <summary>
        /// 首页按钮点击事件
        /// </summary>
        private void BtnFirst_Click(object sender, EventArgs e)
        {
            if (pageIndex != 1)
            {
                pageIndex = 1;
                LoadData();
            }
        }
        
        /// <summary>
        /// 尾页按钮点击事件
        /// </summary>
        private void BtnLast_Click(object sender, EventArgs e)
        {
            if (pageIndex != totalPages && totalPages > 0)
            {
                pageIndex = totalPages;
                LoadData();
            }
        }
        
        /// <summary>
        /// 加载数据方法
        /// </summary>
        private async void LoadData()
        {
            try
            {
                string url = $"api/Consumer/GetConsumer?pageindex={pageIndex}&pagesize={pageSize}";
                
                // 添加查询条件（如果有）
                if (!string.IsNullOrEmpty(textEdit1.Text))
                {
                    url += $"&Consumercode={textEdit1.Text}";
                }
                
                if (!string.IsNullOrEmpty(textEdit2.Text))
                {
                    url += $"&Consumername={textEdit2.Text}";
                }
                
                // 临时保存原始BaseUrl
                string originalBaseUrl = Properties.Settings.Default.BaseUrl;
                try
                {
                    // 临时修改BaseUrl为端口5052
                    Properties.Settings.Default.BaseUrl = "http://localhost:5052/";
                    
                    string result = await HttpClientHelper.RequestUrl(RequestType.Get, url, "");
                    
                    if (!string.IsNullOrEmpty(result))
                    {
                        ConsumerDto dto = JsonConvert.DeserializeObject<ConsumerDto>(result);
                        
                        if (dto != null && dto.Data != null)
                        {
                            gridControl1.DataSource = dto.Data;
                            
                            // 更新分页信息
                            totalCount = dto.TotalCount;
                            totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
                            
                            // 更新页码信息标签，使用更好的格式
                            lblPageInfo.Text = $"总记录数: {totalCount}   总页数: {totalPages}   当前页: {pageIndex}";
                            
                            // 控制按钮状态
                            // 获取首页和尾页按钮
                            Button btnFirst = panelControl3.Controls.OfType<Button>().FirstOrDefault(b => b.Text == "首页");
                            Button btnLast = panelControl3.Controls.OfType<Button>().FirstOrDefault(b => b.Text == "尾页");
                            
                            // 设置按钮状态
                            if (btnFirst != null) btnFirst.Enabled = pageIndex > 1;
                            if (btnLast != null) btnLast.Enabled = pageIndex < totalPages;
                            button3.Enabled = pageIndex > 1;
                            button4.Enabled = pageIndex < totalPages;
                        }
                    }
                }
                finally
                {
                    // 恢复原始BaseUrl
                    Properties.Settings.Default.BaseUrl = originalBaseUrl;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                DevExpress.XtraEditors.ButtonEdit buttonEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                if (buttonEdit == null) return;
                
                // 获取当前行
                var row = gridView1.GetFocusedRow() as Consumermodel;
                if (row == null) return;
                
                // 创建并显示keup窗体，传递客户ID
                keup updateForm = new keup(row.Id);
                updateForm.ShowDialog();
                
                // 如果需要在关闭keup窗体后刷新数据
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开编辑窗口失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                DevExpress.XtraEditors.ButtonEdit buttonEdit = sender as DevExpress.XtraEditors.ButtonEdit;
                if (buttonEdit == null) return;
                
                // 获取当前行
                var row = gridView1.GetFocusedRow() as Consumermodel;
                if (row == null) return;
                
                // 显示确认对话框
                DialogResult result = MessageBox.Show($"确定要删除客户 '{row.Consumername}' 吗？", 
                    "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.Yes)
                {
                    // 调用删除API
                    string url = $"api/Consumer/DeleteConsumer?id={row.Id}";
                    
                    // 临时保存原始BaseUrl
                    string originalBaseUrl = Properties.Settings.Default.BaseUrl;
                    try
                    {
                        // 临时修改BaseUrl为端口5052
                        Properties.Settings.Default.BaseUrl = "http://localhost:5052/";
                        
                        string response = await HttpClientHelper.RequestUrl(RequestType.Put, url, "");
                        
                        // 解析响应
                        if (!string.IsNullOrEmpty(response))
                        {
                            // 可以解析响应JSON获取更多信息
                            dynamic responseObj = JsonConvert.DeserializeObject(response);
                            
                            if (responseObj != null && responseObj.Code != null && responseObj.Code.ToString() == "200")
                            {
                                MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                // 刷新数据
                                LoadData();
                            }
                            else
                            {
                                string errorMsg = responseObj != null && responseObj.Message != null 
                                    ? responseObj.Message.ToString() 
                                    : "未知错误";
                                MessageBox.Show($"删除失败：{errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show("删除失败：未收到服务器响应", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    finally
                    {
                        // 恢复原始BaseUrl
                        Properties.Settings.Default.BaseUrl = originalBaseUrl;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除操作出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                LoadData();
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (pageIndex < totalPages)
            {
                pageIndex++;
                LoadData();
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            pageIndex = 1;  // 重置为第一页
            LoadData();
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建并显示keup窗体，用于新增客户
                keup addForm = new keup();
                DialogResult result = addForm.ShowDialog();
                
                // 如果添加成功，刷新数据列表
                if (result == DialogResult.OK)
                {
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开新增窗口失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 下载文件的异步方法
        /// </summary>
        /// <param name="url">API地址</param>
        /// <param name="fileName">保存的文件名</param>
        /// <returns>下载是否成功</returns>
        private async Task<bool> DownloadFileAsync(string url, string fileName)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址为端口5052
                    client.BaseAddress = new Uri("http://localhost:5052/");
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(60);

                    // 发送GET请求获取文件
                    HttpResponseMessage response = await client.GetAsync(url);

                    // 确保HTTP请求成功
                    if (response.IsSuccessStatusCode)
                    {
                        // 将响应内容写入文件
                        using (var stream = await response.Content.ReadAsStreamAsync())
                        using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                        {
                            await stream.CopyToAsync(fileStream);
                        }
                        return true;
                    }
                    else
                    {
                        Console.WriteLine($"下载文件失败: {response.StatusCode}");
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"下载文件异常: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button5_Click(object sender, EventArgs e)
        {
            try
            {
                // 定义导出Excel的API地址
                string url = "api/Consumer/ExportConsumerToExcel";
                
                // 使用SaveFileDialog让用户选择保存位置
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Excel文件|*.xlsx";
                saveFileDialog.Title = "保存Excel文件";
                saveFileDialog.FileName = "客户数据导出_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
                
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 显示加载提示
                    Cursor = Cursors.WaitCursor;
                    
                    // 调用本地下载方法下载Excel文件
                    bool success = await DownloadFileAsync(url, saveFileDialog.FileName);
                    
                    // 恢复光标
                    Cursor = Cursors.Default;
                    
                    if (success)
                    {
                        MessageBox.Show("导出成功！文件已保存至：" + saveFileDialog.FileName, "导出成功", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        
                        // 在资源管理器中显示并选中文件
                        System.Diagnostics.Process.Start("explorer.exe", "/select," + saveFileDialog.FileName);
                    }
                    else
                    {
                        MessageBox.Show("导出失败，请稍后重试！", "导出失败", 
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出操作出错：{ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
    }
}